<?php
/**
 * Created by PhpStorm.
 * User: mojie126
 * Date: 2017/8/31 0031
 * Time: 上午 10:04
 */

namespace app\index\controller;


use app\common\RSS;
use app\common\secret;
use app\common\verify;
use app\index\model\Users;
use think\Controller;

class RssController extends Controller
{
	public function index($str)
	{
		/*
		 * RSS链接规则：
		 * 默认为永久有效
		 * 自定义有效时间
		 *
		 * 链接全部JWT+自定义加密函数
		 * JWT载荷包含用户ID和UUID
		 */
		$url = verify::decode((secret::decrypt($str)));
		if (!$url) {
			$this->error("链接已失效", "/");
		} else {
			$uuid = $url->sub;
			$uid = $url->uid;
		}
		$res = db("rss")->where("userid", $uid)->select();
		$title = APP_NAME;
		$link = getWebURL();
		$desc = "Torrents From " . APP_NAME;
		$rss = new RSS($title, $link, $desc);
		if ($res) {
			foreach ($res as $k) {
				$db = getTorrentDB($k['type']);
				$where = [
					"id" => $k['torrentid'],
					"type" => $k['type']
				];
				$download_url = getWebURL() . "/dl/" . ($db == 0 ? "m" : "s") . "/$k[torrentid]/$uuid";
				$link = getWebURL() . "/$db/id/$k[torrentid]";
				$t_info = db($db)->where($where)->select();
				foreach ($t_info as $key) {
					$rss->AddItem("<![CDATA[" . $key['maintitle'] . " [size:" . getSize($key['torrentsize']) . "]]]>", $link, $download_url, $key['torrentsize']);
				}
			}
		}
		$rss->Display();
	}

	public function createCustomRSS($ttl = 0)
	{
		if (!is_int($ttl) && $ttl < 0) {
			jsonReturn(0, "TTL值必须是正整数");
		}
		$uuid = Users::getUserUUID(session("uid"));
		if (empty($ttl)) {
			$jwt = verify::encode($uuid, 0, ["uid" => session("uid")]);
		} else {
			$ttl = $ttl * 60;
			$jwt = verify::encode($uuid, $ttl, ["uid" => session("uid")]);
		}
		$secret = secret::encrypt($jwt);
		if ($secret) {
			jsonReturn(1, "生成成功", ["url" => getWebURL() . "/rss/" . $secret]);
		} else {
			jsonReturn(0, "未知错误，请稍后重试");
		}
	}
}